package com.lyz.moil.core.security.service;

import com.lyz.moil.core.orm.hibernate.BaseDao;
import com.lyz.moil.core.orm.hibernate.BaseService;
import com.lyz.moil.core.security.dao.LinkManDao;
import com.lyz.moil.core.security.entity.Department;
import com.lyz.moil.core.security.entity.LinkMan;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

@Service
@Transactional
public class DepartmentService extends BaseService<Department> {

    @Resource
    private LinkManDao linkManDao;

    @Override
    @Resource(name = "departmentDao")
    public void setBaseDao(BaseDao<Department> baseDao) {
        this.baseDao = baseDao;
    }

    private void updateContacts(Department department) {
        String hql = "delete from LinkMan where department.id = ?";
        linkManDao.batchExecute(hql, department.getId());
        if (department.getLinkMans() != null) {
            Set<LinkMan> contacts = new HashSet<LinkMan>();
            for (LinkMan linkMan : department.getLinkMans()) {
                linkMan.setInsertTime(new Date());
                linkMan.setDepartment(department);
                contacts.add(linkMan);
            }
            department.setContacts(contacts);
        }
    }

    @Override
    public void save(Department entity) {
        updateContacts(entity);
        super.save(entity);
    }

    @Override
    public void update(Department entity) {
        updateContacts(entity);
        super.update(entity);
    }
}
